from app.extensions import db
import datetime


class StrGenerationHistory(db.Model):
    """字符串生成历史记录"""
    __tablename__ = 'generation_history'

    id = db.Column(db.Integer, primary_key=True)
    length = db.Column(db.Integer, nullable=False)
    char_type = db.Column(db.String(50), nullable=False)
    prefix = db.Column(db.String(100), default='')
    suffix = db.Column(db.String(100), default='')
    custom_chars = db.Column(db.Text, default='')
    generated_string = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    # 为 MySQL 添加索引以提高查询性能
    __table_args__ = (
        db.Index('idx_char_type', 'char_type'),
        db.Index('idx_created_at', 'created_at'),
    )


    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'length': self.length,
            'char_type': self.char_type,
            'prefix': self.prefix,
            'suffix': self.suffix,
            'custom_chars': self.custom_chars,
            'generated_string': self.generated_string,
            'created_at': self.created_at.isoformat()
        }

    def __repr__(self):
        return f'<GenerationHistory {self.id}>'